import { PlusOutlined } from '@ant-design/icons';
import { Button, Space, Popconfirm, message, Input } from 'antd';
import { history } from 'umi';
import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { caselist, updateCaseNew, updateShareAndView } from './servic';
import type { TableListItem, TableListPagination } from './data';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [countModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [type, setType] = useState<String>();

  /** 国际化配置 */

  const handleShow = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    let item = { id: record.id };
    item.hide = record.hide == 0 ? 1 : 0;
    try {
      const response = await updateCaseNew(item);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current?.reloadAndRest?.();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const handleShareAndView = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    try {
      const response = await updateShareAndView(record);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '医生姓名',
      dataIndex: 'doctorName',
    },
    {
      title: '医院',
      dataIndex: 'hospitalName',
    },
    {
      title: '第一科室',
      dataIndex: 'deptName',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '病例标题',
      dataIndex: 'caseTitle',
    },
    {
      title: '病例来源',
      dataIndex: 'source ',
      width: '150px',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        0: { text: '常规内容' },
        1: { text: '病例活动大赛' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '阅读量',
      dataIndex: 'views',
      hideInForm: true,
      hideInSearch: true,
      render: (dom, record) => (
        <Space>
          <span>{dom}</span>
          <a
            onClick={() => {
              setCurrentRow(record);
              setType('views');
              handleModalVisible(true);
            }}
          >
            修改
          </a>
        </Space>
      ),
    },
    {
      title: '转发量',
      dataIndex: 'shares',
      hideInForm: true,
      hideInSearch: true,
      render: (dom, record) => {
        return (
          <Space>
            <span>{dom}</span>
            <a
              onClick={() => {
                setCurrentRow(record);
                setType('shares');
                handleModalVisible(true);
              }}
            >
              修改
            </a>
          </Space>
        );
      },
    },
    {
      title: '显示状态',
      dataIndex: 'hide',
      width: '100px',
      hideInForm: true,
      hideInSearch: true,
      render: (text, _, index) => {
        return text == 0 ? '显示' : '隐藏';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="detail"
          onClick={() => {
            history.push('/case/case-detail-new?id=' + record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="eidt"
          onClick={() => {
            history.push('/case/case-detail-new?id=' + record.id);
          }}
        >
          删除
        </a>,
        <Popconfirm
          key="top"
          title={record.hide == 0 ? '确定要隐藏吗?' : '确定要显示吗?'}
          onConfirm={() => handleShow(record)}
        >
          <a>{record.hide == 0 ? '隐藏' : '显示'}</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      {countModalVisible ? (
        <ModalForm
          title={'修改'}
          width="500px"
          layout="horizontal"
          visible={countModalVisible}
          onVisibleChange={handleModalVisible}
          onFinish={async (value) => {
            value.type = type;
            value.id = currentRow.id;
            console.log('value', value);
            let success = await handleShareAndView(value as TableListItem);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormDigit
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}
            label="数量"
            width="md"
            min={1}
            name="count"
          />
        </ModalForm>
      ) : null}
      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        editable={{
          type: 'multiple',
        }}
        headerTitle={
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push('/case/case-detail-new');
            }}
          >
            <PlusOutlined /> 新增
          </Button>
        }
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          // console.log(params, sorter, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await caselist({
            pageNum: params.current,
            pageSize: params.pageSize,
          });
          console.log('msg', msg);
          if (msg.code == 200) {
            return {
              data: msg.data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
